package com.zzyang.aop.demo.rpc.consumer;



import com.zzyang.aop.demo.rpc.MyReferenceInvocation;
import com.zzyang.aop.demo.rpc.consumer.netty.ConsumerNettyClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * MyReference 注解代理方法
 *
 * @author zhuoziyang
 * @date 2021/5/19 22:17
 */
public class MyReferenceInvocationHandler implements InvocationHandler {

    private final String url;

    public MyReferenceInvocationHandler(String url) {
        this.url = url;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MyReferenceInvocation invocation = new MyReferenceInvocation();
        Class<?> interfaceName = method.getDeclaringClass();
        invocation.setInterfaceName(interfaceName.getName())
                .setMethodName(method.getName())
                .setArgs(args);

        List<String> argTypes = new ArrayList<>();
        Arrays.stream(method.getParameterTypes()).forEach(argType -> argTypes.add(argType.getName()));
        invocation.setArgTypes(argTypes);
        ConsumerNettyClient consumerClient = new ConsumerNettyClient(url);
        consumerClient.start();

        return consumerClient.send(invocation,method.getReturnType());
    }

}
